package service

import (
	"gorm.io/gorm"
	"zsc-boot/app/customer/model"
	"zsc-boot/app/customer/model/request"
	layerModel "zsc-boot/app/system_layer/model"
	layerSvc "zsc-boot/app/system_layer/service"
	"zsc-boot/core/orm"
)

type OrderSvc struct {
}

func (o *OrderSvc) Create(req model.Order) error {
	return orm.GetDb().Create(&req).Error
}

func (o *OrderSvc) Detail(id uint) (data model.Order, err error) {
	err = orm.GetDb().Where("id = ?", id).Preload("CustomerInfo").Preload("DepInfo").
		Preload("UserInfo").Preload("DepInfo").Preload("OrderAdds.ServiceDocuments").Find(&data).Error
	return
}

func (o *OrderSvc) Update(req model.Order) (err error) {
	err = orm.GetDb().Where("id = ?", req.ID).Updates(&req).Error
	return
}

func (o *OrderSvc) Delete(orderId uint) (err error) {
	err = orm.GetDb().Where("id = ?", orderId).Delete(&model.Order{}).Error
	return
}

func (o *OrderSvc) AllList(req request.OrderMyListReq, userInfo layerModel.ServiceUser) (list []model.Order, count int64, NotMoney, Money int, err error) {
	db := orm.GetDb().Model(&model.Order{})

	if userInfo.Role.Code != "root" {
		//权限控制
		userInfoList := layerSvc.ServiceUsersService.GetSubUsers(userInfo.ID)
		userIds := make([]uint, 0, len(userInfoList))
		if len(userInfoList) > 0 {
			for _, user := range userInfoList {
				userIds = append(userIds, user.ID)
			}
		} else {
			userIds = append(userIds, userInfo.ID) //自已的数据总是可以看的
		}

		db.Where("user_id in (?)", userIds)
	}

	if req.CustomerId != 0 {
		db.Where("customer_id = ?", req.CustomerId)
	}
	if req.CustomerName != "" {
		customerIds := orm.GetDb().Model(&model.Customer{}).Where("name LIKE ?", "%"+req.CustomerName+"%").Select("id")
		db.Where("customer_id IN (?)", customerIds)
	}
	if req.CustomerMobile != "" {
		customerIds := orm.GetDb().Model(&model.Customer{}).Where("mobile LIKE ?", "%"+req.CustomerMobile+"%").Select("id")
		db.Where("customer_id IN (?)", customerIds)
	}
	if req.UserId != 0 {
		db.Where("user_id = ?", req.UserId)
	}
	if req.DepId != 0 {
		//获取子级
		var depModel layerModel.ServiceDepartment
		if err = orm.GetDb().Where("id = ?", req.DepId).Preload("Children.Children.Children").First(&depModel).Error; err != nil {
			return
		}
		depIds := make([]uint, 0)
		depIds = append(depIds, depModel.ID)
		for _, dep := range depModel.Children {
			for _, de := range dep.Children {
				for _, d := range de.Children {
					depIds = append(depIds, d.ID)
				}
				depIds = append(depIds, de.ID)
			}
			depIds = append(depIds, dep.ID)
		}

		db.Where("dep_id in ?", depIds)
	}

	if req.OrderAddStartDate != "" && req.OrderAddEndDate != "" {
		subDb := orm.GetDb().Model(&model.OrderAdd{}).
			Where("pay_date >= ? and pay_date <= ?", req.OrderAddStartDate, req.OrderAddEndDate).
			Select("order_id")
		db.Where("id in (?)", subDb)
	} else {
		if req.SignDateStart != "" {
			db.Where("sign_date >= ?", req.SignDateStart)
		}
		if req.SignDateEnd != "" {
			db.Where("sign_date <= ?", req.SignDateEnd)
		}
	}

	if req.Status != "" {
		db.Where("status = ?", req.Status)
	}
	if req.IsPayOff != nil {
		db.Where("is_pay_off = ?", *req.IsPayOff)
	}
	db1 := db.Session(&gorm.Session{})
	if err = db.Count(&count).Error; err != nil {
		return
	}

	err = db.Preload("CustomerInfo").Preload("OrderAdds", func(db *gorm.DB) *gorm.DB {
		if req.OrderAddStartDate != "" && req.OrderAddEndDate != "" {
			return db.Where("pay_date >= ? and pay_date <= ?",
				req.OrderAddStartDate, req.OrderAddEndDate)
		}
		return db
	}).Preload("OrderAdds.ServiceDocuments").
		Preload("UserInfo").Preload("DepInfo").Order("id desc").
		Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).Find(&list).Error
	for k, _ := range list {
		notMoney := int(list[k].Money)
		for _, v := range list[k].OrderAdds {
			notMoney -= int(v.Money)
		}
		if notMoney <= 0 {
			notMoney = 0
		}
		list[k].NotMoney = notMoney

		var isPayOff bool
		//补偿修改
		if list[k].NotMoney == 0 {
			isPayOff = true
		}

		if isPayOff != list[k].IsPayOff {
			list[k].IsPayOff = isPayOff
			_ = orm.GetDb().Save(&list[k])
		}
	}

	var groupList []model.Order
	err = db1.Preload("CustomerInfo").Preload("OrderAdds", func(db *gorm.DB) *gorm.DB {
		if req.OrderAddStartDate != "" && req.OrderAddEndDate != "" {
			return db.Where("pay_date >= ? and pay_date <= ?",
				req.OrderAddStartDate, req.OrderAddEndDate)
		}
		return db
	}).Preload("OrderAdds.ServiceDocuments").
		Preload("UserInfo").Preload("DepInfo").Order("id desc").
		Find(&groupList).Error
	for k, _ := range groupList {
		notMoney := int(groupList[k].Money)
		for _, v := range groupList[k].OrderAdds {
			notMoney -= int(v.Money)
		}
		if notMoney <= 0 {
			notMoney = 0
		}
		groupList[k].NotMoney = notMoney
	}
	for _, v := range list {
		NotMoney += v.NotMoney
		Money += int(v.Money)
	}

	return
}
